package com.ruoyi.uni.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MD5;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.uni.config.uploadConfig;
import com.ruoyi.uni.domain.DcCustomer;
import com.ruoyi.uni.domain.DcGoods;
import com.ruoyi.uni.domain.DcOrder;
import com.ruoyi.uni.domain.DcTypes;
import com.ruoyi.uni.mapper.DcCustomerMapper;
import com.ruoyi.uni.mapper.DcGoodsMapper;
import com.ruoyi.uni.mapper.DcOrderMapper;
import com.ruoyi.uni.mapper.DcTypesMapper;
import com.ruoyi.uni.service.uniService;
import com.ruoyi.uni.util.CODE;
import com.ruoyi.uni.util.DcCustomerHandle;
import com.ruoyi.uni.util.wxRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;

import java.util.ArrayList;

import java.util.Arrays;
import java.util.List;


@Service
public class uniServiceImpl implements uniService {
    @Autowired
    private wxRequestUtil wxRequestUtil;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private DcCustomerMapper dcCustomerMapper;
    @Autowired
    private DcTypesMapper dcTypesMapper;
    @Autowired
    private DcGoodsMapper dcGoodsMapper;
    @Autowired
    private DcOrderMapper dcOrderMapper;
    @Autowired
    private uploadConfig uploadConfig;

    public AjaxResult login(String jsCode){

        //获取openid
        JSONObject wxReq = wxRequestUtil.getWxLoginReq(jsCode);
        if(wxReq.getString("openid")!=null){
            //获取openid成功
            String openid = wxReq.getString("openid");
            DcCustomer dcCustomer = dcCustomerMapper.selectDcCustomerByOpenId(openid);
            if(dcCustomer==null){
                //未注册
                dcCustomer = new DcCustomer(openid,"HH"+ MD5.MD5_16("HH"),"",1,1);
               dcCustomerMapper.insertDcCustomer(dcCustomer);

            }
                //已注册，给token
                String s = MD5.MD5_16("TO");
                redisCache.setCacheObject(s,dcCustomer);
                redisCache.expire(s,1200);
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("token",s);
                jsonObject.put("userInfo",DcCustomerHandle.filterCu(dcCustomer));
                return AjaxResult.success(jsonObject);
        }
        return AjaxResult.error(CODE.JS_CODE_ERR,"jsCode错误");
    }

    public DcCustomer getDcCustomerByToken(HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        return (DcCustomer) redisCache.getCacheObject(token);
    }

    @Override
    public AjaxResult updateName(String name, Long id) {
        if(dcCustomerMapper.updateName(name,id)>0)
            return AjaxResult.success("修改成功");
        else return AjaxResult.error(CODE.UPDATE_ERR,"修改失败");

    }

    @Override
    public AjaxResult updateSex(Long sex, Long id) {
        if(dcCustomerMapper.updateSex(sex,id)>0)
            return AjaxResult.success("修改成功");
        else return AjaxResult.error(CODE.UPDATE_ERR,"修改失败");
    }

    @Override
    public AjaxResult updateTel(String tel, Long id) {
        if(dcCustomerMapper.updateTel(tel,id)>0)
            return AjaxResult.success("修改成功");
        else return AjaxResult.error(CODE.UPDATE_ERR,"修改失败");
    }

    @Override
    public AjaxResult updateEmail(String email, Long id) {
        if(dcCustomerMapper.updateEmail(email,id)>0)
            return AjaxResult.success("修改成功");
        else return AjaxResult.error(CODE.UPDATE_ERR,"修改失败");
    }

    public AjaxResult selectCustomerById(Long id){
        DcCustomer dcCustomer = dcCustomerMapper.selectDcCustomerById(id);
        DcCustomer filterCu = DcCustomerHandle.filterCu(dcCustomer);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("userInfo",filterCu);
        return AjaxResult.success(jsonObject);
    }

    public AjaxResult getTypeList(){
        List<DcTypes> dcTypes = dcTypesMapper.selectDcTypesList(null);
        for(DcTypes dc:dcTypes){
            dc.setDcGoodsList(dcGoodsMapper.selectDcGoodsByType(dc.getId()));
        }
        return AjaxResult.success(dcTypes);
    }

    public AjaxResult submitOrder(JSONObject j,HttpServletRequest httpServletRequest){
         String cart= j.getString("goodCart");
         int tableId=j.getInteger("tableId");
        List<DcGoods> dc = JSONArray.parseArray(cart, DcGoods.class);

        String token = httpServletRequest.getHeader("token");
        DcCustomer customer = redisCache.getCacheObject(token);

        DcOrder dcZero = dcOrderMapper.selectOrderByStatusZero(customer.getId());

        if(dcZero!=null){
            return AjaxResult.error("还有未支付的订单",dcZero.getId());
        }

        long count=0;
       BigDecimal amount=new BigDecimal(0);
        JSONArray jsonArray=new JSONArray();
        for(DcGoods dcGoods:dc){
            DcGoods Goods = dcGoodsMapper.selectDcGoodsById(dcGoods.getId());
            if(Goods!=null){
                jsonArray.add(dcGoods);
                count+=dcGoods.getNum();
                amount= (Goods.getPrice().multiply(BigDecimal.valueOf(dcGoods.getNum()))).add(amount);
            }

        }
        String orderId=MD5.MD5_16("order");
        DcOrder dcOrder=new DcOrder(tableId,orderId,customer.getId(), jsonArray.toString(),0,amount, DateUtils.getNowDate());
        System.out.println(dcOrder);
         dcOrderMapper.insertDcOrder(dcOrder);
        JSONObject o=new JSONObject();
        o.put("rmbtotal",amount);
        o.put("orderId",orderId);
        JSONObject ret=new JSONObject();
        ret.put("order",o);
        return AjaxResult.success(ret);
    }
    //由于没有微信收费权限，只能模拟支付，直接修改订单状态
    public AjaxResult pay(String orderId){
        dcOrderMapper.updateStatusAndPayTime(1,DateUtils.getNowDate(),orderId);
        DcOrder dcOrder = dcOrderMapper.selectDcOrderById(orderId);
        List<DcGoods> goodIds= JSONArray.parseArray(dcOrder.getGoodsId(),DcGoods.class);
        for (DcGoods dc:goodIds){
            DcGoods newGood = dcGoodsMapper.selectDcGoodsById(dc.getId());
            newGood.setCount(newGood.getCount()+1L);
            dcGoodsMapper.updateDcGoods(newGood);
        }
        return AjaxResult.success("支付成功");
    }
    public AjaxResult getOrderDetailById(String orderId){
        DcOrder dcOrder = dcOrderMapper.selectDcOrderById(orderId);

        List<DcGoods> goodIds= JSONArray.parseArray(dcOrder.getGoodsId(),DcGoods.class);
        List<DcGoods> goodsList=new ArrayList<>();

        for (DcGoods good:goodIds){
           DcGoods dcGoods = dcGoodsMapper.selectDcGoodsById(good.getId());
           dcGoods.setNum(good.getNum());
             goodsList.add(dcGoods);
        }
        dcOrder.setDcGoodsList(goodsList);
        dcOrder.setGoodsId(null);
        return AjaxResult.success("success",dcOrder);
    }

    public AjaxResult selectOrderByStatus(int status,HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        DcCustomer dcCustomer =(DcCustomer) redisCache.getCacheObject(token);
        List<DcOrder> dcOrders = dcOrderMapper.selectByStatus(status, dcCustomer.getId());
        for (DcOrder dcOrder:dcOrders){
            List<DcGoods> goodIds= JSONArray.parseArray(dcOrder.getGoodsId(),DcGoods.class);
            List<DcGoods> newGood=new ArrayList<>();
            for (DcGoods good : goodIds){
                DcGoods dcGoods = dcGoodsMapper.selectDcGoodsById(good.getId());
                dcGoods.setNum(good.getNum());
                newGood.add(dcGoods);
            }
            dcOrder.setDcGoodsList(newGood);
            dcOrder.setGoodsId(null);
        }

        return AjaxResult.success(dcOrders);
    }

    public AjaxResult cancelOrder(String id)
    {
        return AjaxResult.success(dcOrderMapper.updateStatus(-2,id));
    }

    public AjaxResult updateCover(String avatarUrl,HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        DcCustomer dcCustomer =(DcCustomer) redisCache.getCacheObject(token);
        int i = dcCustomerMapper.updateCover(avatarUrl, dcCustomer.getId());
        if(i>0)
            return AjaxResult.success("upload cover success");
        return AjaxResult.error(CODE.UPDATE_ERR,"update cover error");
    }

}
